package com.fsh.anime.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsh.anime.mapper.EmployeeMapper;
import com.fsh.anime.model.dtos.EmpLoginDto;
import com.fsh.anime.model.pojos.Employee;
import com.fsh.anime.model.vos.Result;
import com.fsh.anime.service.EmployeeService;
import com.fsh.anime.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 登录
     *
     * @param dto dto
     * @return {@link Result}
     */
    @Override
    public Result login(EmpLoginDto dto) {
        //校验参数 - 自动校验

        //比对 数据库 name 和 密码
        LambdaQueryWrapper<Employee> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getName,dto.getName());
        lambdaQueryWrapper.eq(Employee::getPassword, DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()));
        Employee employee = employeeMapper.selectOne(lambdaQueryWrapper);
        if (employee==null){
            return Result.error("用户不存在或密码错误");
        }
        //封装自定义信息
        Map<String,Object> claims=new HashMap<>();
        claims.put("id",employee.getId());
        claims.put("role",employee.getRole());
        //使用JWT工具类，生成身份令牌
        String token = JwtUtil.getToken(claims);
        return Result.success(token,"登陆成功");
    }
}
